package com.cvit.weixin;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.w3c.dom.Document;

import com.cvit.model.Msg;
import com.cvit.model.Orders;
import com.cvit.model.Student;
import com.cvit.service.OrdersService;
import com.cvit.service.StudentService;
import com.cvit.utils.Utils;

@Controller
public class WeiXinController {
	@Autowired
	OrdersService ordersService;
	@Autowired
	StudentService studentService;
	/**
     * 微信统一下单接口
     * @param
     * @param 
     * 
     */
   @RequestMapping("/weixinpay")
   @ResponseBody
   public Msg WeiXinpay(Student student ,HttpServletResponse resp,HttpServletRequest request) throws IOException{
	   Map<String, Object> map=new HashMap<String, Object>();
	   Map<String, Object> returnMap=new HashMap<String, Object>();
	   DataInputStream input = null;  
	 /*  SimpleDateFormat sf = new SimpleDateFormat("yyMMddHHmmss");
	   Date newdate=new Date();
	   String dateS=sf.format(newdate);*/
	   String name=student.getName();
	   String eamineeId =student.getEamineeId();
	   String baseUrl="http://bmjf.dz.cvit.com.cn";
	   String body="长春职业技术学院-单独招生报名费-"+name+"-"+eamineeId;
	   String out_trade_no=ordersService.JudgeIdRepeat();
	   java.io.ByteArrayOutputStream out = null;
	   HttpServletRequest httpServletRequest = (HttpServletRequest)request;
	   String spbill_create_ip= httpServletRequest.getRemoteAddr();
	   try{    
	   map.put("appid", ConfigUtil.appid);
	   map.put("mch_id", ConfigUtil.mch_id);
	   map.put("sub_appid", ConfigUtil.sub_appid);
	   map.put("sub_mch_id", ConfigUtil.sub_mch_id);
	   map.put("device_info", "WEB");
	   map.put("nonce_str", Utils.getUUID());
	   map.put("sign_type", "MD5");
	   map.put("body",body);
	   map.put("out_trade_no",out_trade_no);
	   map.put("total_fee", 20000);
	   map.put("spbill_create_ip", spbill_create_ip);
	   map.put("notify_url", baseUrl+"/weixincallback");
	   map.put("trade_type", "NATIVE");
	   map.put("product_id", student.getId());
	   map.put("limit_pay", "no_credit");
	   String sign = Signature.getSign(map, ConfigUtil.key);
	   map.put("sign", sign);
	   String xmlString = WXXmlSp.getXmlOrder(map);
			byte[] xmlData = xmlString.getBytes("UTF-8");
			String urlStr = ConfigUtil.UNIFIED_ORDER_URL;
			// 获得到位置服务的链接  
		//	String result = PayCommonUtil.httpsRequest(ConfigUtil.UNIFIED_ORDER_URL, "POST", requestXML);
			URL url = new URL(urlStr);
			HttpURLConnection connection = (HttpURLConnection)url.openConnection();    
			//URLConnection urlCon = url.openConnection();
			connection.setRequestMethod("POST");  
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			// 将xml数据发送到位置服务
			connection.setRequestProperty("Content-Type", "text/xml");
			connection.setRequestProperty("Content-length",
					String.valueOf(xmlData.length));
			DataOutputStream printout = new DataOutputStream(
					connection.getOutputStream());
			printout.write(xmlData);
			printout.flush();
			printout.close();
			input = new DataInputStream(connection.getInputStream());
			byte[] rResult;
			out = new java.io.ByteArrayOutputStream();
			byte[] bufferByte = new byte[256];
			int l = -1;
			int downloadSize = 0;
			while ((l = input.read(bufferByte)) > -1) {
				downloadSize += l;
				out.write(bufferByte, 0, l);
				out.flush();
			}
			rResult = out.toByteArray();
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document d = db.parse(new ByteArrayInputStream(rResult));
			String return_code = d.getElementsByTagName("return_code").item(0).getFirstChild().getNodeValue();
			String result_code="";
			if(return_code.equals("SUCCESS")){
				result_code = d.getElementsByTagName("result_code").item(0).getFirstChild().getNodeValue();}
			if("SUCCESS".equals(return_code)&&"SUCCESS".equals(result_code)){
				Orders orders = new Orders();
				orders.setId(out_trade_no);
				orders.setBody(body);
				orders.setStudentId(student.getId());
				orders.setSpbillCreateIp(spbill_create_ip);
				String id = ordersService.addOrders(orders);
				//returnMap.put("recode", "1");product_id
				System.out.println("成功:"+d.getElementsByTagName("prepay_id").item(0).getFirstChild().getNodeValue());
				System.out.println("成功:"+d.getElementsByTagName("code_url").item(0).getFirstChild().getNodeValue());
				returnMap.put("out_trade_no",id);
				returnMap.put("prepayid", d.getElementsByTagName("prepay_id").item(0).getFirstChild().getNodeValue());
				returnMap.put("code_url", d.getElementsByTagName("code_url").item(0).getFirstChild().getNodeValue());
				returnMap.put("body", body);
				
			}else{
				//returnMap.put("recode", "0");
				if(!return_code.equals("SUCCESS")){
					System.out.println("return失败:"+d.getElementsByTagName("return_msg").item(0).getFirstChild().getNodeValue());
					returnMap.put("msg", d.getElementsByTagName("return_msg").item(0).getFirstChild().getNodeValue());
				}else if(!result_code.equals("SUCCESS")){
					System.out.println("result失败:"+d.getElementsByTagName("err_code_des").item(0).getFirstChild().getNodeValue());
					returnMap.put("msg", d.getElementsByTagName("err_code_des").item(0).getFirstChild().getNodeValue());
				}
				
				
			}
			
		} catch (Exception e){
			//returnMap.put("recode", "2");
			e.printStackTrace();
		} finally {
			out.close();
			input.close();
		}
		//return returnMap;
	   return Msg.success().add("returnMap",returnMap); 
   }
   @RequestMapping("/weixincallback")
   @ResponseBody
    public String WeiXinCallBack(HttpServletResponse resp,HttpServletRequest reques){
    	System.out.println("***微信回调start");
		try {
			ServletInputStream input=reques.getInputStream();
			byte[] rResult;
			ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
			byte[] bufferByte = new byte[256];
			int l = -1;
			int downloadSize = 0;
			while ((l = input.read(bufferByte)) > -1) {
				downloadSize += l;
				out.write(bufferByte, 0, l);
				out.flush();
			}
			rResult = out.toByteArray();
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document d = db.parse(new ByteArrayInputStream(rResult));
			String return_code = d.getElementsByTagName("return_code").item(0).getFirstChild().getNodeValue();
			String result_code = d.getElementsByTagName("result_code").item(0).getFirstChild().getNodeValue();
	//		String product_id=d.getElementsByTagName("product_id").item(0).getFirstChild().getNodeValue();
			System.out.println("微信回调return_code:"+return_code);
			System.out.println("微信回调result_code:"+result_code);
		//	System.out.println("微信回调product_id:"+product_id);
			if("SUCCESS".equals(return_code)&&"SUCCESS".equals(result_code)){
				String orderId=d.getElementsByTagName("out_trade_no").item(0).getFirstChild().getNodeValue();
				System.out.println("订单ID:"+orderId);
				//修改订单表状态
				Orders orders = new Orders();
				Student student=new Student();
				orders.setId(orderId);
				orders.setType(1);
				ordersService.updateOrders(orders);
				String student_id=ordersService.selectStudentIdById(orderId);
				int tyte =studentService.updatePayByEamineeId(student_id);
				resp.getWriter().write(WXXmlSp.getXmlOrderResult(return_code, result_code));
			}
			
		} catch (Exception e) {
			System.out.println("***微信回调Exception");
		}
		System.out.println("***微信回调end");
	   return null;
    }
	/**
	 * @author WYHY
	 * @param 关闭订单
	 * */
	@RequestMapping("/close")
	public String close(HttpServletRequest request, HttpServletResponse response,String orderid) throws IOException{
		   //log4j--star
			//log4j--end
		   Map<String, Object> map=new HashMap<String, Object>();
		   Map<String, Object> returnMap=new HashMap<String, Object>();
		   DataInputStream input = null;  
		   java.io.ByteArrayOutputStream out = null;
		   try{    
			   map.put("appid", ConfigUtil.appid);
			   map.put("mch_id", ConfigUtil.mch_id);
			   map.put("sub_appid", ConfigUtil.sub_appid);
			   map.put("sub_mch_id", ConfigUtil.sub_mch_id);
			   map.put("out_trade_no",orderid);
			   map.put("nonce_str", orderid);
			   String sign = Signature.getSign(map, ConfigUtil.key);
			   map.put("sign", sign);
			   String xmlString = WXXmlSp.getCloseXmlOrder(map);
			   //log4j--star
				//log4j--end
				byte[] xmlData = xmlString.getBytes("UTF-8");
				String urlStr = "https://api.mch.weixin.qq.com/pay/closeorder";
				URL url = new URL(urlStr);
				HttpURLConnection connection = (HttpURLConnection)url.openConnection();    
				connection.setRequestMethod("POST");  
				connection.setDoOutput(true);
				connection.setDoInput(true);
				connection.setUseCaches(false);
				// 将xml数据发送到位置服务
				connection.setRequestProperty("Content-Type", "text/xml");
				connection.setRequestProperty("Content-length",
						String.valueOf(xmlData.length));
				DataOutputStream printout = new DataOutputStream(
						connection.getOutputStream());
				printout.write(xmlData);
				printout.flush();
				printout.close();
				input = new DataInputStream(connection.getInputStream());
				byte[] rResult;
				out = new java.io.ByteArrayOutputStream();
				byte[] bufferByte = new byte[256];
				int l = -1;
				int downloadSize = 0;
				while ((l = input.read(bufferByte)) > -1) {
					downloadSize += l;
					out.write(bufferByte, 0, l);
					out.flush();
				}
				rResult = out.toByteArray();
				DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
				DocumentBuilder db = dbf.newDocumentBuilder();
				Document d = db.parse(new ByteArrayInputStream(rResult));
				String return_code = d.getElementsByTagName("return_code").item(0).getFirstChild().getNodeValue();
				String result_code="";
				if(return_code.equals("SUCCESS")){
					result_code = d.getElementsByTagName("result_code").item(0).getFirstChild().getNodeValue();
				}
				if ("SUCCESS".equals(return_code) && "SUCCESS".equals(result_code)){
					System.out.println("return成功 :"+d.getElementsByTagName("return_msg").item(0).getFirstChild().getNodeValue());
				}else{
					if(!return_code.equals("SUCCESS")){
						System.out.println("return失败:"+d.getElementsByTagName("return_msg").item(0).getFirstChild().getNodeValue());
						returnMap.put("msg", d.getElementsByTagName("return_msg").item(0).getFirstChild().getNodeValue());
					}else if(!result_code.equals("SUCCESS")){
						System.out.println("result失败:"+d.getElementsByTagName("err_code_des").item(0).getFirstChild().getNodeValue());
						returnMap.put("msg", d.getElementsByTagName("err_code_des").item(0).getFirstChild().getNodeValue());
					}
					
				}
				
			} catch (Exception e){
				//returnMap.put("recode", "2");
				e.printStackTrace();
			} finally {
				out.close();
				input.close();
			}
		return null;
	}
  
}
